<template>
  <div style="display: flex;  flex-direction: column;">
    <div style="display: flex; margin-top: -20px">
      <el-button type="primary" @click="handleAdd" style="margin-top: 15px"><i class="el-icon-circle-plus-outline"></i>添加角色</el-button>
    </div>
    <div style="display: flex; margin-top: 20px">
      <el-table :data="tableData" style="width: 100%" height="450">
        <el-table-column fixed label="序号" >
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" ></el-table-column>
        <el-table-column prop="roleDescription" label="角色描述" ></el-table-column>
        <el-table-column prop="count" label="用户数量"></el-table-column>
        <el-table-column label="启用状态">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                @change="handleStatusChange(scope.row)"
                :active-value="1"
                :inactive-value="0">

            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="info" @click="selectMenu(scope.row.roleId)">分配菜单<i class="el-icon-menu"></i></el-button>
            <el-button type="warning" @click="handleDel(scope.row.roleId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="padding: 10px 0;margin-left: 800px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          :page-sizes="[5, 10, 15, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
<!--    添加角色-->
    <el-dialog :visible.sync="dialogFormVisible" :custom-class="'slide-right-dialog'">
      <div class="dialog-content">
        <div class="dialog-title">
          <span>添加角色</span>
        </div>
        <el-form :model="form" :rules="rules" :ref="form" label-width="100px" class="demo-ruleForm">
          <el-form-item label="角色名称" prop="projectNumber">
            <el-input v-model="form.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="projectName">
            <el-input v-model="form.roleDescription"></el-input>
          </el-form-item>
          <el-form-item label="是否启用" prop="status">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="项目类型" prop="budget">
            <el-input v-model="form.budget"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="save">确定</el-button>
            <el-button @click="reset">重置</el-button>
            <el-button @click="dialogFormVisible = false">取 消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
<!--    编辑角色-->
    <el-dialog :visible.sync="menuDialogVis" :custom-class="'slide-right-dialog'">
      <div class="dialog-content">
        <div class="dialog-title">
          <span>权限分配</span>
        </div>
        <el-form :model="form" :rules="rules" :ref="form" label-width="100px" class="demo-ruleForm">
          <el-tree
              :props="props"
              :data="menuData"
              show-checkbox
              node-key="menuId"
              ref="tree"
              :default-expanded-keys="expends"
              :default-checked-keys="checks">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span><i :class="data.menuIcon"></i>{{ data.menuName}}</span>
              </span>
          </el-tree>
          <el-form-item>
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRoleMenu">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {getRolePage,deleteRole,addRole,getMenu,saveRoleMenu,getRoleMenu} from "@/api/role";
import {findMenuIds} from "@/api/menu";
import {getUserCountByRole} from "@/api/user";

export default {
  name: 'RoleList',
  data() {
    return {
      tableData: [],
      pageNum: 1,
      total: 0,
      pageSize: 5,
      dialogFormVisible: false,
      menuDialogVis: false,
      menuData: [],
      roleId: 0,
      props: {
        label: 'menuName'
      },
      expends: [],
      checks: [],
      form: {
        roleName: '',
        roleDescription: '',
        status: 1,
      },
      statusOptions: [
        {label: '是', value: 1},
        {label: '否', value: 0},
      ],
      rules: {}
    }
  },
  created() {
    this.init();
  },
  methods: {
    async init() {//初始化页面
      await getRolePage(this.pageNum, this.pageSize).then(res => {
        const roles = res.records;

        getUserCountByRole().then(counts => {
          const promises = roles.map(role => {
            const count = counts.find(r => r.roleId === role.roleId)
            role.count = count ? count.userCount : 0
          })

          Promise.all(promises).then(() => {
            this.tableData = roles;
            console.log(this.tableData);
            this.total = res.total;
          })
        })

      })
    },
    handleStatusChange(row){
      addRole(row).then(res => {
        if(res) {
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
      })

    },
    handleDel(id) {
      // 添加确认提示
      this.$confirm('确定要删除这个角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户确认删除后执行删除操作
        deleteRole(id).then(res => {
          if (res) {
            this.$message.success('删除成功')
            this.init()
          } else {
            this.$message.error('操作失败')
          }
        })
      }).catch(() => {
        // 用户取消删除时的操作
        this.$message.info('删除已取消')
      })
    },
    handleSizeChange(val) {//改变页码
      this.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {//改变每页显示条数
      this.pageNum = val;
      this.init();
    },
    handleAdd() {//添加
      this.dialogFormVisible=true
      this.form={
        roleName: '',
        roleDescription: '',
        status: 1,
      }
    },
    //handleCheckChange(data, checked, indeterminate) {
    //  },
    save() {//确定
      addRole(this.form).then(res => {
        if(res) {
          this.$message.success('操作成功')
          this.dialogFormVisible=false
          this.init()
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    reset() {//重置表单
      this.form={
        roleName: '',
        roleDescription: '',
        status: 1,
      }
    },
    saveRoleMenu(){
      saveRoleMenu(this.roleId,this.$refs.tree.getCheckedKeys()).then(res => {
        if(res) {
          this.$message.success('权限设置成功')
          this.menuDialogVis = false

          //操作管理员角色的时候需要重新登录
          if(this.roleId === 1) {
            this.$store.commit('logout')
          }

        } else {
          this.$message.error('操作失败')
        }
      })
    },
    selectMenu(roleId){
      this.menuDialogVis = true
      this.roleId = roleId

      // 请求菜单数据
      getMenu().then(res => {
        this.menuData = res.data;

        this.expends = this.menuData.map(item => item.menuId)
      })

      getRoleMenu(roleId).then(res => {
        this.checks = res.data

        //找到当前角色所有的菜单id，不显示没有的菜单
        findMenuIds().then(r => {
          const ids = r.data
          ids.forEach(id => {
            if(!this.checks.includes(id)) {
              //可能会报错
              this.$refs.tree.setChecked(id, false)
            }
          })

        })
      })
    },
  }
};
</script>

<style scoped>
>>> .slide-right-dialog {
  top: -150px;
  right: 0;
  margin: 0;
  position: absolute;
  height: 900px;
  width: 600px;
  animation: slide-right 0.3s ease;
}

>>> .slide-right-dialog .el-dialog__title {
  font-size: 20px; /* 调整对话框正文内容的字体大小 */
}
</style>
